# -*- coding:utf-8 -*-
"""
" ip2region python seacher client module
"
" Autho: koma<komazhang@foxmail.com>
" Date : 2015-11-06
"""
from __future__ import unicode_literals

import _thread
import time

import searchIP
import HFUTcoure
from flask import Flask
from flask import request
from flask import jsonify
from flask import g
#from flask_cors import cross_origin
timeleft = 0
flag = True
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
#app.config['SERVER_NAME'] ='api.iou.ink'

@app.route('/')
def hello_world():
    global flag
    global timeleft
    if flag:
        try:
            _thread.start_new_thread(counttime, ())
            print("thread start")
        except:
            print("error thread")
    if timeleft:
        return "counting"+str(timeleft)
    else:
        timeleft+=120
        return 'access [心.top] for more message.\n access [./ip-js] or [./ip-json] to get different user data.'+str(timeleft)


@app.route("/ip-json", methods=["GET"])
def ipjson():
    ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    try:
        dict1 = searchIP.testSearch(ip)
        dict2 = {'ip': ip}
        dnew = Merge(dict2, dict1)
        print(dnew)
        return jsonify(dnew), 200
    except:
        return jsonify({"Error": "查询ip:" + str(ip) + "失败"}), 200


@app.route("/ip-js", methods=["GET"])
def ipjs():
    ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    try:
        dict1 = searchIP.testSearch(ip)
        dict2 = {'ip': ip}
        dnew = Merge(dict2, dict1)
        strrr = "var ip_data =" + str(dnew)
        return strrr, 200
    except:
        return "var ip_data =" +str({"Error": "查询ip:" + str(ip) + "失败"}),200



@app.route("/HFUTcourse/<data>", methods=["GET", "POST"])
def rtcoursedata(data):
    username = request.args.get('name', default = '', type = str)
    password = request.args.get('passwd', default = '', type = str)
    if username  and password:
        if data == "getcourse":
            try:
                HFUTcoure.get(username,password).login().set().get_lesson()
            except Exception as e:
                print("errreq:", e)
        elif data == "getuserdata":
            try:
                HFUTcoure.get(username,password).login().set().getUserdata()
            except Exception as e:
                print("errreq2:", e)
    else:
        g.return_data = {"error": "请输入账号和密码"}
    return jsonify(g.return_data),200

def counttime():
    global timeleft
    global flag
    if timeleft != 0:
        flag =False
        timeleft = timeleft - 1
        print("timenow" , timeleft)
        time.sleep(1)
        counttime()
    else:
        print("timenow---0")
        flag = True
        time.sleep(4)
        counttime()
def callback(data):
    g.return_data=data


def Merge(dict1, dict2):
    res = {**dict1, **dict2}
    return res



if __name__ == "__main__":
    app.run(
        host="127.0.0.1",
        #155.94.158.151
        port=int("10746"),
        #ssl_context=('/root/py/IPtoregion2/cert/fullchain.pem', '/root/py/IPtoregion2/cert/private.key'),
        debug=True
    )
